import { CallHandler, ExecutionContext, ForbiddenException, Injectable, NestInterceptor } from '@nestjs/common';
import { Observable } from 'rxjs';
import * as process from 'node:process';
import { ConfigService } from '@nestjs/config';


@Injectable()
export class PreventModifyTestDataInterceptor implements NestInterceptor {

  constructor(private readonly configService: ConfigService) {
  }

  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const request = context.switchToHttp().getRequest();

    const isDemoENV = process.env.NODE_ENV === 'demo';
    const isIncludesMethod = ['POST', 'PUT', 'DELETE', 'PATCH'].includes(request.method);
    const isIncludesPath = request.url.includes(this.configService.get<string[]>('auth-ignore.whitelist'));

    if (isDemoENV && isIncludesMethod && isIncludesPath) {
      throw new ForbiddenException('演示环境禁止修改或删除数据');
    }
    return next.handle();
  }
}
